<template>
  <el-row class="login-container" justify="center" align="middle">
    <el-card style="max-width: 480px">
      <template #header>
        <div class="card-header">
          <img :src="imgUrl" alt="" />
        </div>
      </template>
      <div class="jump-link">
        <el-link type="primary" @click="hannleChange"
          >{{ formType ? "返回登陆" : "注册账号" }}
        </el-link>
      </div>
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        style="max-width: 600px"
        class="demo-ruleForm"
        :rules="rules"
      >
        <el-form-item prop="userName">
          <el-input
            v-model="loginForm.userName"
            aria-placeholder="手机号"
            prefix-icon="UserFilled"
          />
        </el-form-item>
        <el-form-item prop="passWord">
          <el-input
            v-model="loginForm.passWord"
            type="password"
            aria-placeholder="密码"
            prefix-icon="Lock"
          />
        </el-form-item>
        <el-form-item prop="validCode" v-if="formType">
          <el-input
            v-model="loginForm.validCode"
            aria-placeholder="验证码"
            prefix-icon="lock"
            style="cursor: pointer"
          >
            <template #append>
              <span @click="countdownChange">{{ countdown.validText }}</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            style="width: 100%"
            @click="submitForm(loginFormRef)"
          >
            {{ formType ? "注册" : "登陆" }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </el-row>
</template>

<script setup>
import { ref, reactive } from "vue";
import { useRouter } from "vue-router";
import { getCode, register, login } from "@/api/index";
const imgUrl = new URL("../../../public/login-head.png", import.meta.url).href;

//路由实例
const router = useRouter();
// 表单数据
const loginForm = reactive({
  userName: "",
  passWord: "",
  validCode: "",
});

//切换表单(0登陆,1注册)
const formType = ref(0);

//点击切换登陆函数
const hannleChange = () => {
  formType.value = !formType.value;
};
//账号校验规则
const validateUser = (rule, value, callback) => {
  //校验账号不为空
  if (value === "") {
    return callback(new Error("账号不能为空"));
  } else {
    const phoneReg =
      /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
    phoneReg.test(value)
      ? callback()
      : callback(new Error("请输入正确的手机号"));
  }
};
//密码校验规则
const validatePass = (rule, value, callback) => {
  if (value === "") {
    return callback(new Error("密码不能为空"));
  } else {
    const passReg = /^[a-zA-Z0-9_-]{4,16}$/;
    passReg.test(value)
      ? callback()
      : callback(new Error("密码为4-16位数字、字母、下划线"));
  }
};
//表单校验
const rules = reactive({
  userName: [{ validator: validateUser, trigger: "blur" }],
  password: [{ validator: validatePass, trigger: "blur" }],
});

//发送短信
const countdown = reactive({
  validText: "获取验证码",
  time: 60,
});
let flag = false;
const countdownChange = () => {
  //倒计时
  if (flag) return;
  const phoneReg =
    /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}$/;
  if (!loginForm.userName || !phoneReg.test(loginForm.userName)) {
    return ElMessage({
      message: "请输入正确的手机号",
      type: "warning",
    });
  }
  //立即执行一次
  countdown.validText = "剩余" + countdown.time + "秒";
  const timer = setInterval(() => {
    if (countdown.time <= 0) {
      countdown.validText = "获取验证码";
      countdown.time = 60;
      flag = false;
      clearInterval(timer);
    } else {
      countdown.time--;
      countdown.validText = `剩余${countdown.time}秒`;
    }
  }, 1000);
  flag = true;
  getCode({ tel: loginForm.userName }).then(({ data }) => {
    console.log("data:", data);
    if (data.code == 10000) {
      ElMessage.success("发送成功");
    }
  });
};

const loginFormRef = ref();
//表单提交
const submitForm = async (formEl) => {
  if (!formEl) return;
  // 校验表单
  await  formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      //注册页面
      if (formType.value) {
        register(loginForm).then(({data}) => {
          if (data.code === 10000) {
            ElMessage.error("注册成功,请登录");
            formType.value = 0;
          }
        });
        console.log("loginForm:", loginForm)
      } else {
        //登录页面
        login(loginForm).then(({data}) => {
          if (data.code == 10000) {
            ElMessage.error("登录成功");
            //将token和用户信息缓存在本地
            localStorage.setItem("pz_token", data.data.token);
            localStorage.setItem(
              "pz_userInfo",
              JSON.stringify(data.data.userInfo)
            );
            router.push("/");
          }
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
</script>

<style lang="less" scoped>
:deep(.el-card__header) {
  padding: 0;
}
.login-container {
  height: 100%;
  .card-header {
    background-color: #899fe1;
    img {
      width: 430px;
    }
  }
  .jump-link {
    text-align: right;
    margin-bottom: 10px;
  }
}
</style>
